<?php

namespace seecms\lib;

use seecms\See;

class UserPermission
{

    protected $user_id = '';

    protected $permission = [];

    public function __construct($user_id)
    {
        $this->user_id = $user_id;

        if ($user_id) {
            $this->find();
        }
    }

    public static function init($user_id): UserPermission
    {
        return new self($user_id);
    }

    public function find()
    {
        if (empty($this->permission)) {
            $permission = See::table()->user_permission->where('user_id', $this->user_id)->find();
            foreach (['role', 'menu', 'rule'] as $item) {
                if ($permission[$item] ?? '') {
                    $permission[$item] = explode(',', $permission[$item]);
                }
            }
            $this->permission = $permission;
        }

        return $this->permission;
    }

    public function get()
    {
        return $this->permission;
    }

    public function role()
    {
        return $this->permission['role'] ?? [];
    }

    public function menu()
    {
        return $this->permission['menu'] ?? [];
    }

    public function rule()
    {
        return $this->permission['rule'] ?? [];
    }
}